package huu.phong.youtube;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;

public class VideoImage extends ImageIcon {

	private static final long serialVersionUID = 2122710715121355814L;
	private static final int DEFAULT_WIDTH = 120;
	private static final int DEFAULT_HEIGHT = 90;
	public String duration;
	public boolean hd;
	private int width;
	private int height;
	private static final Color DEFAULT_HD_COLOR = new Color(150, 150, 150);
	
	public VideoImage(URL url, String duration){
		super(url);
		this.duration = duration;
	}
	
	public VideoImage(URL url, String duration, boolean hd){
		super(url);
		this.duration = duration;
		this.hd = hd;
	}
	
	public VideoImage(String link, String duration) throws MalformedURLException{
		super(new URL(link));
		this.duration = duration;
	}
	
	public VideoImage(String link, String duration, boolean hd) throws MalformedURLException{
		super(new URL(link));
		this.duration = duration;
		this.hd = hd;
	}
	
	public VideoImage(Image image, String duration){
		super(image);
		this.duration = duration;
	}
	
	public synchronized void paintIcon(Component c, Graphics g, int x, int y){
		Graphics2D g2 = (Graphics2D) g;
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
		g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
		g2.drawImage(getImage(), 0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT, getImageObserver());
		g2.setFont(YouTube.DEFAULT_FONT);
		width = SwingUtilities.computeStringWidth(g2.getFontMetrics(), duration);
		height = g2.getFontMetrics().getAscent() - g2.getFontMetrics().getDescent();
	    g2.setColor(YouTube.DEFAULT_BACKGROUND);
		g2.fillRoundRect(getIconWidth() - (width + 8), getIconHeight() - (height + 8), width + 6, height + 6, 5, 5);
		g2.setColor(Color.WHITE);
	    g2.drawString(duration, getIconWidth() - (width + 5), getIconHeight() - 5);
	    if (hd){
	    	width = SwingUtilities.computeStringWidth(g2.getFontMetrics(), "HD");
	    	g2.setColor(YouTube.DEFAULT_BACKGROUND);
			g2.fillRoundRect(1, getIconHeight() - (height + 8), width + 6, height + 6, 5, 5);
		    g2.setColor(DEFAULT_HD_COLOR);
			g2.drawString("HD", 5, getIconHeight() - 5);
	    }
	}
	
	public int getIconWidth(){
		return DEFAULT_WIDTH;
	}
	
	public int getIconHeight(){
		return DEFAULT_HEIGHT;
	}
}
